////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009 Daniel F. Hanson
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace SilverLua.Runtime
{
   /// <summary>
   /// A runtime environment for one or more scripts. Each environment has its
   /// own global table, though access to the global tables of other
   /// environments is allowed through the VM.
   /// </summary>
   internal class Environment
   {
      internal string Name { get; private set; }
      internal Table GlobalTable { get; private set; }

      private Dictionary<string, Script> _scripts = new Dictionary<string, Script>();
      internal VirtualMachine VirtualMachine { get { return _vm; } private set { _vm = value; } }
      internal static VirtualMachine _vm = null;
      
      private Stopwatch _stopwatch = new Stopwatch();
      private Queue<Script> _scheduleQueue = new Queue<Script>();

      internal bool IsPaused = false;
      
      private Dictionary<Type, Table> _prototypes = new Dictionary<Type, Table>();
      
      internal Environment(VirtualMachine vm, string name, Table globalTable)
      {
         VirtualMachine = vm;
         Name = name;
         GlobalTable = globalTable;

         Table math = new Table();
         math[new Value("floor")] = new Value(typeof(Environment).GetMethod("Floor", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic));
         GlobalTable[new Value("math")] = new Value(math);
         GlobalTable[new Value("table")] = new Value(new Table());
      }
      
      private static int Floor(float num)
      {
         return (int)Math.Floor(num);
      }
      
      private static Stopwatch stopwatch = new Stopwatch();

      internal Script LoadScript(ScriptBinary scriptBinary, bool autoStart)
      {
         Script script = new Script(this, scriptBinary.Chunks, 32);
         
         if (autoStart)
         {
            script.Start();
         }
         
         return script;
      }
      
      internal void RunScript(Script script)
      {
         _scheduleQueue.Enqueue(script);
      }
      
      internal void Update(TimeSpan maxTime)
      {
         _stopwatch.Reset();
         _stopwatch.Start();
         
         while ((maxTime == TimeSpan.Zero || _stopwatch.Elapsed < maxTime) && _scheduleQueue.Count > 0)
         {
            Script script = _scheduleQueue.Dequeue();
            
            if (script.State == ScriptState.Running)
            {
               script.DoTimeslice();
            }
            
            if (script.State != ScriptState.Done)
            {
               _scheduleQueue.Enqueue(script);
            }
         }
         
         _stopwatch.Stop();
      }
      
      internal void AddType(Type type, Table prototype)
      {
         _prototypes.Add(type, prototype);
      }
      
      internal Table GeneratePrototype(Type type, object obj)
      {
         Table basePrototype = _prototypes[type];
         Table prototype = new Table();
         
         foreach (KeyValuePair<Value, Value> entry in basePrototype)
         {
            if (entry.Value.Type == ValueType.HostField)
            {
               HostField hostField = entry.Value.GetHostField();
               prototype[entry.Key] = new Value(hostField, obj);
            }
            else if (entry.Value.Type == ValueType.HostFieldHelper)
            {
               HostFieldHelper hostField = entry.Value.GetHostFieldHelper();
               prototype[entry.Key] = new Value(hostField, obj);
            }
            else if (entry.Value.Type == ValueType.HostProperty)
            {
               HostProperty hostProperty = entry.Value.GetHostProperty();
               prototype[entry.Key] = new Value(hostProperty, obj);
            }
            else
            {
               prototype[entry.Key] = entry.Value;
            }
         }
         
         return prototype;
      }
   }
}
